package com.zut.edu;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.longer.verifyedittext.PhoneCode;
import com.mob.MobSDK;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
import com.zut.edu.bean.Page;
import com.zut.edu.bean.User;
import com.zut.edu.http.BaseCallback;
import com.zut.edu.http.OkhttpHelper;
import com.zut.edu.utils.StringUtils;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import okhttp3.Call;
import okhttp3.Response;

public class RegisterSecondActivity extends AppCompatActivity implements View.OnClickListener{

    @BindView(R.id.verification_code)
    PhoneCode verificationcode;
    @BindView(R.id.register_second_button)
    QMUIRoundButton registersecondbutton;
    @BindView(R.id.get_phone_code)
    TextView getphonecode;
    @BindView(R.id.registersecond_back)
    ImageView registersecondback;
    @BindView(R.id.registersecond_phone)
    TextView registersecondphone;
    private TimeCount timeCount;
    private EventHandler handler;
    private String phone;
    private String type;
    private String code;
    public static RegisterSecondActivity instance;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registersecond);
        instance=this;
        QMUIStatusBarHelper.translucent(this);//沉浸式
        QMUIStatusBarHelper.setStatusBarLightMode(this);
        ButterKnife.bind(this);
        MobSDK.init(this,"32a842048844c","6218667fbfa1c2cb4cedfc47581836eb");
        MessageEventBack();
        Intent intent = getIntent();
        phone = intent.getStringExtra("phone");
        type = intent.getStringExtra("type");
//        switch (type){
//            case "register":
//                Intent intent1 = new Intent(RegisterSecondActivity.this,RegisterThirdActivity.class);
//                intent1.putExtra("phone",phone);
//                startActivity(intent1);
//                finish();
//                break;
//            case "tologin":
//                toLogin(phone);
//                break;
//            case "appeal":
//                Intent intent2 = new Intent(RegisterSecondActivity.this,AppealActivity.class);
//                intent2.putExtra("phone",phone);
//                startActivity(intent2);
//                finish();
//            default:
//                break;
//        }
        Log.e("T",type);
        autoFirst(phone);//删
        registersecondphone.setText("+86  "+phone);
        setListener();
    }
    private void setListener(){
        registersecondbutton.setOnClickListener(this);
        registersecondbutton.setChangeAlphaWhenPress(true);
        getphonecode.setOnClickListener(this);
        registersecondback.setOnClickListener(this);
        verificationcode.setOnVCodeCompleteListener(new PhoneCode.OnVCodeInputListener() {
            @Override
            public void vCodeComplete(String verificationCode) {
                code = verificationCode;
            }
            @Override
            public void vCodeIncomplete(String verificationCode) {
            }
        });
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.register_second_button:
                if(code.length()!=6){
                    Toast.makeText(this,"请输入验证码", Toast.LENGTH_SHORT).show();
                    return;
                }
                SMSSDK.submitVerificationCode("86",phone,code);
                break;
            case R.id.registersecond_back:
                super.onBackPressed();
                break;
            case R.id.get_phone_code:
                SMSSDK.getVerificationCode("86",phone);
                timeCount = new TimeCount(60000, 1000);
                timeCount.start();
                break;
        }
    }
    public void MessageEventBack(){
        handler = new EventHandler(){
            @Override
            public void afterEvent(int event, int result, Object data) {
                if (result == SMSSDK.RESULT_COMPLETE){
                    //回调完成
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        //提交的验证码正确
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                switch (type){
                                    case "register":
                                        Intent intent1 = new Intent(RegisterSecondActivity.this,RegisterThirdActivity.class);
                                        intent1.putExtra("phone",phone);
                                        startActivity(intent1);
                                        finish();
                                        break;
                                    case "tologin":
                                        toLogin(phone);
                                        break;
                                    case "appeal":
                                        Intent intent2 = new Intent(RegisterSecondActivity.this,AppealActivity.class);
                                        intent2.putExtra("phone",phone);
                                        startActivity(intent2);
                                        finish();
                                        break;
                                    default:
                                        break;
                                }
                            }
                        });

                    }else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE){
                        //获取验证码成功
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(RegisterSecondActivity.this,"验证码已发送", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES){
                    }
                }else{
                    ((Throwable)data).printStackTrace();
                    Throwable throwable = (Throwable) data;
                    try {
                        JSONObject obj = new JSONObject(throwable.getMessage());
                        final String des = obj.optString("detail");
                        if (!TextUtils.isEmpty(des)){
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(RegisterSecondActivity.this,"验证码错误", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }
        };

        SMSSDK.registerEventHandler(handler);
    }

    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            getphonecode.setClickable(false);
            getphonecode.setText("("+millisUntilFinished / 1000 +"S)重新发送");
        }

        @Override
        public void onFinish() {
            getphonecode.setText("获取验证码");
            getphonecode.setClickable(true);

        }
    }

    private void autoFirst(String phonenum){
        if(phonenum.length()==11){
            SMSSDK.getVerificationCode("86",phonenum);
            timeCount = new TimeCount(60000, 1000);
            timeCount.start();
        }
    }

    private void toLogin(String phone){
        OkhttpHelper okhttpHelper = OkhttpHelper.getInstance();
        Map<String,Object> params = new HashMap<>(1);
        params.put("userAccount",phone);
        okhttpHelper.get(StringUtils.BASE_URL + "/user/query", params, new BaseCallback<Page<User>>() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

            @Override
            public void onSuccess(@NotNull Call call, @NotNull Response response, Page<User> userPage, int code) throws IOException {
                String user_data = com.alibaba.fastjson.JSONObject.toJSONString(userPage.getList().get(0));
                SharedPreferences sp = getSharedPreferences("nfc_pre",MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();
                editor.putString("user",user_data);
                editor.commit();

                switch (userPage.getList().get(0).userIdentity){
                    case "2":
                        Intent login = new Intent(RegisterSecondActivity.this,MainActivity.class);
                        login.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(login);
                        finish();
                        break;
                    default:
                        Intent login2 = new Intent(RegisterSecondActivity.this,MainOpActivity.class);
                        login2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(login2);
                        finish();
                        break;
                }
            }


            @Override
            public void onError(@NotNull Call call, @NotNull Response response, int code, Exception e) {

            }
        });
    }
}
